package com.example.springboot.controller;

import com.example.springboot.bean.Department;
import com.example.springboot.service.DeptService;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.locks.InterProcessSemaphoreMutex;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * zookeeper实现分布式锁
 *
 * @Author:ChenZhangKun
 * @Date: 2021/5/24 14:42
 */
@RestController
@RequestMapping("/zookeeper")
public class ZookeeperController {
    @Autowired
    private CuratorFramework client;
    @Autowired
    private DeptService deptService;

    @GetMapping("/save")
    public Department save(@RequestParam("name") String name) throws InterruptedException {
        // 创建分布式锁操作器
        InterProcessSemaphoreMutex baseMutex = new InterProcessSemaphoreMutex(client, "/zktest/" + name);
        Department department = new Department();
        try {
            // 执行加锁操作
            baseMutex.acquire();
            //
            System.out.println("已经加锁了" + name);
            // 后面是原子性操作
            department.setDepartmentName(name);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 释放锁
            TimeUnit.SECONDS.sleep(20);
            try {
                baseMutex.release();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        // 保存
        deptService.insertDept(department);
        return department;
    }
}
